package code.tools.log
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.XMLSocket;
	import flash.utils.Timer;
	
	/**
	 * @author wenqiang.deng
	 */
	public class LogTargetSos implements ILogTarget
	{
		public function output(level : LogLevel, loggerName : String, message : String, error : Error = null) : void
		{
			var out : String = loggerName + ': ' + message;
			if (_socket.connected)
				_socket.send(formatMessage(level.name, out, error));
			else
			{
				_caches.push([level.name,out,error]);
				if(_caches.length>CACHE_MAX)
					_caches.shift();
			}
		}
		
		private var _host : String;
		private var _port : uint;
		private var _ticker : Timer;
		private var _socket : XMLSocket;
		//sos连接成功前信息缓存
		private static const CACHE_MAX:int = 200;
		private var _caches:Array;
		
		public function LogTargetSos(host : String = '127.0.0.1', port : uint = 4444)
		{
			_caches = new Array();
			_host = host;
			_port = port;
			_ticker = new Timer(20000);
			_ticker.addEventListener(TimerEvent.TIMER, onTick);
			_ticker.start()
			_socket = new XMLSocket();
			_socket.addEventListener(Event.CONNECT, onConnect);
			_socket.addEventListener(Event.CLOSE, onClose);
			_socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
			_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
			_socket.addEventListener(ProgressEvent.SOCKET_DATA, onData);
			_socket.connect(_host, _port);
			onTick();
		}
		
		private function onTick(event : TimerEvent = null) : void
		{
			if (!_socket.connected)
			{
				_socket.connect(_host, _port);
			}
		}
		
		private function onConnect(event : Event) : void
		{
			trace('[LOG]:SOS连接成功');
			_ticker.stop();
			var len:int = _caches.length;
			for(var i:int =0;i<len;i++)
				_socket.send(formatMessage(_caches[i][0], _caches[i][1], _caches[i][2]));
			_caches.length = 0;
		}
		
		private function onClose(event : Event) : void
		{
			trace('[LOG]:SOS连接关闭');
			_ticker.reset();
			_ticker.start();
		}
		
		private function onError(event : Event) : void
		{
			trace('[LOG]:SOS连接错误');
			_ticker.reset();
			_ticker.start();
		}
		
		private function onData(event : ProgressEvent) : void
		{
			trace('[LOG]:来自SOS的未知信息');
		}
		
		private function formatMessage(key : String, message : String, err : Error) : String
		{
			var command : String;
			if (!err)
				command = '!SOS<showMessage key="' + key + '"><![CDATA[' + message + ']]></showMessage>';
			else
				command = '!SOS<showFoldMessage key="' + key + '"><title><![CDATA[' + message + ']]></title><message><![CDATA[' + err.getStackTrace().substring(6) + ']]></message></showFoldMessage>';
			return command;
		}
	}
}
